<?php
namespace Pinenut\Log;

use Pinenut\Log;

class File extends Log {
	protected static $fileName = null;
	protected static $tempFileName = null;

	public static function commit($title, $data = null, $level = 'log', $file = "", $line = 0, $beginTime = null, $endTime = null) {
		$marker = '~PNT-LOG~';
		$time = date(DATE_ATOM, microtime(true));
		$pid = posix_getpid();

		$content = "$marker $level $time $title\n";
		if (!empty($data)) $content .= print_r($data, true)."\n\n";

		if (static::$fileName === null) {
			$defaultLogFile = \Application::logFile();
			$logFileName = basename($defaultLogFile);
			$actionName = null;

			if (\Dispatcher::$currentContext != null) {
				$context = \Dispatcher::$currentContext;
				if ($context->mainRequest !== null && $context->mainRequest->action !== null) {
					$actionName = $context->mainRequest->action;
				}
			}

			$logFileName = $actionName ?: $logFileName;

			$logDir = dirname($defaultLogFile) . "/$logFileName";
			$fileName =  $logDir . "/{$time}_{$pid}.log";

			if (!file_exists($logDir) && !mkdir($logDir, 0755, true)) {
				return;
			}

			if ($actionName) {
				static::$fileName = $fileName;
				# если существовал неопределенный файл - копируем его в нужное место
				if (!empty(static::$tempFileName)) {
					if (copy(static::$tempFileName, static::$fileName)) {
						unlink(static::$tempFileName);
					}
				}
			} elseif(static::$tempFileName == null) {
				static::$tempFileName = $fileName;
			}
		}

		$logFileName = static::$fileName ?: static::$tempFileName;
		file_put_contents($logFileName, $content, FILE_APPEND);
	}

	static function beginGroup($title = null) {}

	static function endGroup() {}

	static protected function profile($group, $beginTime, $endTime, $title, $data = null, $level = 0) {}
}
